<template>
  <div class="home-page">
    <!-- 全局加载状态 -->
    <div v-if="globalLoading" class="global-loading">
      <!-- 轮播图骨架屏 -->
      <div class="skeleton-banner">
        <div class="skeleton-slide"></div>
      </div>

      <div class="content-wrapper">
        <!-- 各个模块的骨架屏 -->
        <SkeletonScreen type="list" :count="6" />
        <SkeletonScreen type="list" :count="6" />
        <SkeletonScreen type="list" :count="6" />
      </div>
    </div>

    <!-- 正常内容 -->
    <template v-else>
      <!-- 轮播图 -->
      <HomeBanner />

      <div class="content-wrapper">
        <!-- 推荐商品 -->
        <RecommendProducts />

        <!-- 热销商品 -->
        <HotProducts />

        <!-- 新品推荐 -->
        <NewProducts />
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated, onDeactivated, onUnmounted } from 'vue'

// 设置组件名称，用于keep-alive匹配
defineOptions({
  name: 'HomePage',
})
import HomeBanner from './components/HomeBanner.vue'
import HotProducts from './components/HotProducts.vue'
import NewProducts from './components/NewProducts.vue'
import RecommendProducts from './components/RecommendProducts.vue'
import SkeletonScreen from '@/components/common/SkeletonScreen.vue'

const globalLoading = ref(true)
const isFirstLoad = ref(true)
// 使用sessionStorage持久化滚动位置
const scrollPosition = ref(parseInt(sessionStorage.getItem('homeScrollPosition') || '0'))

onMounted(() => {
  // 只在首次加载时执行
  if (isFirstLoad.value) {
    // 模拟全局加载
    setTimeout(() => {
      globalLoading.value = false
      isFirstLoad.value = false
    }, 2000)
  }
})

// keep-alive 组件激活时
onActivated(() => {
  const savedPosition = parseInt(sessionStorage.getItem('homeScrollPosition') || '0')
  console.log('首页被激活，准备恢复滚动位置:', savedPosition)

  if (savedPosition > 0) {
    let lastDocumentHeight = 0

    // 使用更智能的恢复策略：等待页面稳定后滚动
    const attemptSmartRestore = (retryCount = 0) => {
      const MAX_RETRIES = 10
      const currentScroll = window.scrollY
      const documentHeight = document.documentElement.scrollHeight

      // 检查页面是否稳定（高度变化小于50px在最近2次检查中）
      if (
        retryCount >= MAX_RETRIES ||
        (retryCount > 1 && Math.abs(documentHeight - lastDocumentHeight) < 50)
      ) {
        console.log('页面已稳定，执行滚动恢复:', {
          尝试次数: retryCount,
          保存位置: savedPosition,
          当前滚动: currentScroll,
          文档高度: documentHeight,
          稳定性: Math.abs(documentHeight - lastDocumentHeight),
        })

        // 确保在合理范围内滚动
        const safePosition = Math.min(savedPosition, documentHeight - 100)
        if (Math.abs(currentScroll - safePosition) > 50) {
          window.scrollTo({ top: safePosition, behavior: 'smooth' })
        }
        return
      }

      // 记录当前文档高度用于下次比较
      lastDocumentHeight = documentHeight

      // 继续等待
      setTimeout(() => attemptSmartRestore(retryCount + 1), 100)
    }

    // 开始智能恢复
    setTimeout(() => attemptSmartRestore(), 200)
  }
})

// keep-alive 组件停用时
onDeactivated(() => {
  // 确保获取最新的滚动位置
  const getAccuratePosition = () => {
    const currentPosition =
      window.scrollY || document.documentElement.scrollTop || document.body.scrollTop
    sessionStorage.setItem('homeScrollPosition', currentPosition.toString())
    scrollPosition.value = currentPosition
    console.log('首页被停用，保存滚动位置:', currentPosition)
  }

  // 延迟一点确保位置准确
  setTimeout(getAccuratePosition, 50)
})

// 监听页面滚动，实时更新位置
const handleScroll = () => {
  const currentPosition = window.scrollY
  scrollPosition.value = currentPosition
  // 实时保存到sessionStorage
  sessionStorage.setItem('homeScrollPosition', currentPosition.toString())
}

// 简单的防抖函数
const createDebounce = (func: Function, delay: number) => {
  let timeoutId: ReturnType<typeof setTimeout> | null = null
  return (...args: any[]) => {
    if (timeoutId) {
      clearTimeout(timeoutId)
    }
    timeoutId = setTimeout(() => func.apply(this, args), delay)
  }
}

// 防抖处理，避免频繁更新（100ms）
const debouncedScroll = createDebounce(handleScroll, 100)

onMounted(() => {
  window.addEventListener('scroll', debouncedScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', debouncedScroll)
})
</script>

<style scoped lang="scss">
.home-page {
  .global-loading {
    .skeleton-banner {
      width: 100%;
      height: 300px;
      margin-bottom: 30px;

      .skeleton-slide {
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: shimmer 1.5s infinite;
        border-radius: 12px;
      }
    }

    .content-wrapper {
      margin-top: 30px;
      display: flex;
      flex-direction: column;
      gap: 40px;
    }
  }

  .content-wrapper {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    gap: 40px;
  }
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}
</style>
